<template>
	<div>
		<!-- <m-pay :money="totalMoney" :payClick="payClick" :goBack="goBack" :walletMoney="walletMoney" :walletBalance="walletBalance" :thirdPayMoney="thirdPayMoney" @changeWalletMoney="changeWalletMoneyEvent" :orderType="orderType">
		</m-pay>
		<passward-panel ref="passwardPanel" @passwordPendingChange="passwordPendingChangeEvent">
		</passward-panel> -->
	</div>
</template>

<script>
	import Pay from "../../real-components/Pay/otherPay";
	import * as way from "../../config/pay-way";
    import {getOrderInfoByH5Pay} from "./axios";
	import { mapGetters } from "vuex";
	import getOrderInfo from "../../api/gw/getOrderInfo";
	import { getWalletBalance, walletPay } from "./axios";
	import { showLoading, hideLoading } from "../../utils/loading.js";
	import ValidatorFn from "../../utils/ValidatorFn"; //校验axios返回的数据是否合法
	import axios from "axios";
	import * as api from "../../api/gw/index.js";
	import md5 from "js-md5";
	import { Toast } from "../../utils/toast";
	import passwardPanel from "../../real-components/ConfirmOrder/ConfirmOrderPursekey"; //钱包支付密码面板
	import * as orderTypeCode from "../../config/orderTypeCode";
	export default {
		props: {},
		data() {
			return {
				orderMoney: 0, //调翌支付的金额
				payClick: () => {},
				payParams: null, //翌支付相关的参数,
				totalMoney: 0, //所有金额
				walletMoney: 0, //钱包金额
				walletMoneyState: false,
				walletBalance: 0, //钱包余额,
				thirdPayMoney: 0, //第三方支付（翌支付）的金额,
				pwPendingResult: {
					pwPendingState: true, //默认为true，代表在等待
					result: "initial",
					msg: ""
				}, //等待密码校验的对象
				isPaying: false, //是否正在支付中
			}
		},
		computed: {
			...mapGetters("gw", [
				"getPayWay"
			]),
			...mapGetters("wxh", [
				"userInfo"
			]),
			orderNo() {
				this.$route.params.orderNo && localStorage.setItem("orderNo", this.$route.params.orderNo);
				return this.$route.params.orderNo || localStorage.getItem("orderNo");
			},
			//订单类型，线上订单为2（跳转到待配送），线下订单为1（跳转到全部）,礼品卡为12
			orderType() {
				// this.$route.params.orderType && localStorage.setItem("orderType", this.$route.params.orderType);
				// // return this.$route.params.orderType ? this.$route.params.orderType : orderTypeCode.normal;
				// return Number(this.$route.params.orderType) || Number(localStorage.getItem("orderType"));
				return Number(this.$route.params.orderType)
			},
			otherPayParam() {
				this.$route.params.param && localStorage.setItem("PayParam", this.$route.params.param);
				return this.$route.params.param;
			},
			//获取设备类型
			phoneType() {
                let u = navigator.userAgent;
				let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android
				let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios
				return isAndroid ? "Android" : "iOS";
			},
			//钱包支付选中状态
			walletChoosed() {
				return this.getPayWay.join(",").indexOf(way.wallet) > -1;
			},
			//翌支付选中状态
			yizhifuChoosed() {
				return this.getPayWay.join(",").indexOf(way.yizhifu) > -1;
			},
			//获取会员免密金额
			moneyWithoutCode() {
				return this.userInfo.moneyWithoutCode;
			},
			returnUrl() {
				return "https://" + window.location.hostname + "/static/NJ/H5/index.html" + window.location.hash;
			}
		},
		methods: {
			goBack() {
				// 跳转到待支付页面
				if(this.orderType === orderTypeCode.lipinquan) {
					this.$router.replace({
						"name": "buyGiftCard"
					});
					return;
				}
				this.$router.replace({
					"name": "order",
					query: {
						orderStatus: 1
					}
				});
			},
			//判断是否在可配送时间内
			getTimeRight() {
				let p = this.otherPayParam || localStorage.getItem("PayParam");
				console.log("去重新选择时间", p);
				return new Promise((resolve, reject) => {
					getOrderInfoByH5Pay({param: p}).then(res => {
						let obj = {code: res.data.returnCode, msg: res.data.msg || '该订单配送时间已经失效啦'};
						console.log("获取到的obj", obj);
						resolve(obj);
					}).catch(err => {
						resolve({
							code: 3, 
							msg: "服务器正忙"
						});
					});
				});
			},
			//定义处理异常错误的加工厂
			defaultErrorResolve() {
				return {
					//如果没有订单编号，默认跳转到个人中心
					orderNoError() {
						this.$router.replace({
							name: "profile"
						});
					}
				}
			},
			//处理成功后的跳转逻辑
			handlePaySuccessfully() {
				return {
					goResultPage: () => {
						// console.log("this.orderType", this.orderType)
						// console.log("this.orderType === 12", this.orderType === 12)
						if(this.orderType === orderTypeCode.lipinquan) {
							//跳转回礼品卡页面
							// console.log("这里要跳转回礼品卡页面");
							this.$router.replace({
								name: "buyGiftCard",
								params: {
									orderType: this.orderType
								}
							});
						} else if(this.orderType === orderTypeCode.saomagou) {
							//核销页面
							// console.log("这里要跳转回核销页面");
							this.$router.replace({
								name: "scanOrder",
								query: {
									scanOrder: this.orderNo
								}
							
							});
						} else {
							this.$router.replace({
								name: "paysuccessfully",
								params: {
									orderType: this.orderType
								}
							});
						}
					}
				}
			},
			//初始化支付插件
			initPayPlugin() {
				let SEPayPlugin_Start = () => {
					//初始化
					cordova.require('cordova/channel').onCordovaReady.subscribe(function() {
						//  在安卓 进入后 在注册这个方法的时候 和安卓那边就已经调用这个方法了；
						//alert("start to pay 2, exec SEPayPlugin  ");
						cordova.exec(null, null, 'SEPayPlugin', null, []);
						//CenterCommandPlugin('start');
						doPay();
					});
				}
				let SEPayPlugin = (params, sucFunc, failFunc, opts, className) => {
					var params = params || null;
					var sucFunc = sucFunc || function() {};
					var failFunc = failFunc || function() {};
					var opts = opts || {};
					var className = className || null;
					try {
						console.log("11111111");
						cordova.exec(sucFunc, failFunc, "SEPayPlugin", this.phoneType === "Android" ? "doPay" : "start", [className, params, opts]);
					} catch(err) {
						alert("如您在app中进行支付，程序调起支付app失败，请点击按钮手动尝试下！")
					}
				}
				let doPay = () => {
					let data = {
						pay_no: this.payParams.pay_no,
						created_ts: this.payParams.created_ts,
						se_sign: this.payParams.se_sign,
						use_json: '0',
						order_money: this.payParams.amount
					}
					var pay = "sePay" + JSON.stringify(data);
					//配置支付后的回调
					SEPayPlugin(pay,
						() => {
							console.log("支付回调", "支付成功");
							this.handlePaySuccessfully().goResultPage();
							// this.$router.replace({"name": "paysuccessfully", params: {orderType: this.orderType}});
						},
						() => {
							console.log("支付失败");
							Toast({
								message: '支付取消',
								type: "warn",
								duration: 1000
							});
						}
					);
				}

				return SEPayPlugin_Start;
			},
			//禁用支付点击事件
			disablePayClick() {
				this.isPaying = true;
				this.enablePayClick(1000);
			},
			//开启支付点击事件
			enablePayClick(time = 0) {
				setTimeout(() => {
					this.isPaying = false;
				}, time)
			},
			//初始化翌支付的参数
			initPayParams(params) {
				//一个公共方法
				let getParams = (listData) => {
					var pay_no = listData.pay_no;
					var app_code = listData.app_code;
					var se_payment_code = listData.se_payment_code;
					var se_private_key = listData.se_private_key;
					var created_ts = Date.parse(new Date()) / 1000; //
					var amount = listData.amount;
					var appStr = app_code + se_payment_code + pay_no + created_ts;
					var semd5 = md5(appStr) + se_private_key;
					var se_sign = md5(semd5);
					return {
						pay_no,
						created_ts,
						se_sign,
						amount
					}
				}
				//如果是一个字符串，则params是一个订单号，需要去请求数据来初始化参数
				return new Promise((resolve, reject) => {
					let options = {
						method: "post",
						url: window.api.trade_host + api.H5_PAY_PARAMS,
						data: {
							sessionId: localStorage.getItem("sessionId"),
							bill_id: params,
							bill_type_id: "2",
							scenary_id: "2",
							walletMoney: parseFloat(this.walletMoney), //当前用户选择的钱包支付金额
							thirdPartyMoney: parseFloat(this.totalMoney), //当前用户选择的翌支付金额，
							return_url: this.returnUrl
						}
					}
					axios(options).then(data => {
						console.log("请求支付用的参数", data);
						if(data.status === 200) {
							if(data.data.returnCode !== 1) {
								hideLoading();
								this.mToastFn(data.data.msg, 2000);
								resolve(false);
								return;
							}
							//给翌支付所需的参数赋值
							let result = getParams(data.data.data[0]);
							this.payParams = {
								pay_no: result.pay_no,
								created_ts: result.created_ts,
								se_sign: result.se_sign,
								amount: result.amount
							}
							resolve(result);
						} else {
							hideLoading();
							this.mToastFn("请求服务失败", 2000);
							resolve(false);
						}
					}).catch(err => {
						hideLoading();
						this.mToastFn(err.toString(), 2000);
						console.log(err);
						resolve(false);
					});
				});
			},
            //初始化h5支付
            async initH5Pay() {
                //处理异常错误
                // if (!this.orderNo) {
                //     this.defaultErrorResolve()[orderNoError];
                //     return;
                // }
                //获取订单信息
                //判断小周的方法，是否需要重新选择下单时间
                // this.payClick = async () => {
                    //获取当前支付方式、支付前置状态以及支付前置信息
                    // let beforePayInfo = this.judgePayWay(); //拿到一个对象
                    // console.log("支付方式：" + beforePayInfo.way);
                    // if(!beforePayInfo.state) {
                    //     //支付前置状态不成功
                    //     this.mToastFn(beforePayInfo.msg);
                    //     return;
                    // }
                    //如果handleMoneySituationState为false，这是一个短路操作，不会重新去选择时间
                    //订单金额为0的不会重新选择时间
					let timeResult = await this.getTimeRight();
					console.log("timeResult", timeResult);
                    // console.log("timeState", timeState);
                    if (timeResult.code !== 1) {
						//重新去选择时间
						hideLoading();
						this.mToastFn(`${timeResult.msg}  请联系您的好友哦~`, 2000);
                        return;
					}
                    //根据金额判断是否需要调起翌支付的接口
                    //如果handleMoneySituationState为false，代表订单金额为0，直接跳转到支付成功页面
                    //这种情况一般是使用了优惠券，抵扣订单金额为0
                    //并结束掉操作
                    // if (!handleMoneySituationState) {
                    //     //直接跳转到支付成功页面
                    //     this.handlePaySuccessfully().goResultPage();
                    //     return;
					// }
					await this.initPayParams(this.orderNo);
					console.log("调用paynose");
					// return;
                    //拼装支付跳转链接
                    let payUrl = `https://pay.weilian.cn/payment/pay?pay_no=${this.payParams.pay_no}&created_ts=${this.payParams.created_ts}&se_sign=${this.payParams.se_sign}`;
                    // console.log(payUrl);
					hideLoading();
                    //跳转到支付链接
					// location.href = payUrl;
					location.replace(payUrl);
                // }
            },
			//根据不同的金额类型判断不同的处理情况
			handleMoneySituation() {
				return new Promise((resolve, reject) => {
					//订单金额为0不用再去选择时间
					//目前只有使用优惠券全部抵扣的情况下，订单金额才为0
					if(parseFloat(this.totalMoney) > 0) {
						resolve(true);
					} else if(parseFloat(this.totalMoney) === 0) {
						resolve(false);
					}
				})
			},
			//初始化钱包余额
			initWalletBalance() {
				return new Promise(async(resolve, reject) => {
					let data = await getWalletBalance();
					// console.log("这是钱包余额", data);
					if(ValidatorFn(data)) {
						//返回值合法
						// this.walletBalance = 
						// console.log("这是钱包余额", data);
						this.walletBalance = (data.data.data[0].availAmount).toFixed(2);
					}
				});
			},
			//初始化页面数据（包含订单金额以及钱包余额）
			async initData() {
				//获取订单金额
				// let orderInfo = await getOrderInfo(this.orderNo);
				let param = this.otherPayParam ? this.otherPayParam : localStorage.getItem("PayParam")
				let orderInfo = await getOrderInfoByH5Pay({param});
				console.log("orderInfo", orderInfo);
				if (orderInfo.status === 200 && orderInfo.data.returnCode === 2) {
                    //支付成功了
					hideLoading();
					// this.handlePaySuccessfully().goResultPage();
					this.mToastFn("支付成功啦！赶快告诉您的好友吧~", 2000, "success");
					setTimeout(() => {
						this.$router.push({name: "home"});
					}, 2000);
                    return;
                }
                if (orderInfo.status !== 200 || orderInfo.data.returnCode === 0) {
					hideLoading();
					this.mToastFn("当前订单已经失效", 2000, "warn");
					setTimeout(() => {
						this.$router.push({name: "home"});
					}, 2000);
					return;
                }
				//订单总额赋值
				this.totalMoney = (orderInfo.data.data[0].realPay).toFixed(2);
				//初始换各支付方式选中情况和金额信息
				// this.initPayWayState();
                this.initH5Pay();
			},
			//初始换各支付方式选中情况和金额信息
			initPayWayState() {
                this.$store.commit("gw/setPayWay", [way.yizhifu]);
			},
			//判断各种支付方式相加是否合法，返回一个对象
			//{state: true, msg: "", way: ""}
			judgePayWay() {
				//已经对钱包金额大于订单金额做了校验
				//如果两者都没选中
				if(!this.walletChoosed && !this.yizhifuChoosed) {
					return {
						state: false,
						msg: "请选择支付方式",
						way: ""
					}
				}
				//如果钱包支付金额=订单总金额，则为钱包全额支付
				if(parseFloat(this.walletMoney) === parseFloat(this.totalMoney)) {
					console.log("钱包全额支付");
					return {
						state: true,
						msg: "使用钱包全额支付",
						way: way.wallet
					}
				}
				//如果钱包余额为0，则只能选择用翌支付进行支付
				if(parseFloat(this.walletBalance) === 0) {
					return {
						state: true,
						msg: "使用翌支付全额支付",
						way: way.yizhifu
					}
				}
				//如果钱包余额大于0，并且选择用了钱包支付和翌支付，但是不是全额
				if(parseFloat(this.walletMoney) < parseFloat(this.totalMoney) && this.yizhifuChoosed) {
					return {
						state: true,
						msg: "使用混合支付",
						way: way.mixins
					}
				}
				//支付金额不够
				if(parseFloat(this.walletMoney) < parseFloat(this.totalMoney) && !this.yizhifuChoosed) {
					return {
						state: false,
						msg: "请选择足够的金额进行支付",
						way: ""
					}
				}
			},
			//子组件在改变钱包支付金额的时候，触发的回调函数
			changeWalletMoneyEvent(val) {
				// console.log("改变钱包金额", val);
				this.walletMoney = val;
				// if (this.yizhifuChoosed) {
				if(val === "") {
					this.thirdPayMoney = this.totalMoney;
				} else {
					this.thirdPayMoney = (parseFloat(this.totalMoney) - parseFloat(this.walletMoney)).toFixed(2);
				}
				// }

			},
			//判断是否在免密范围内
			judgeFreePassword() {
				// return false;
				// console.log("this.moneyWithoutCode", this.moneyWithoutCode);
				// console.log("parseFloat(this.moneyWithoutCode)", parseFloat(this.moneyWithoutCode));
				// console.log("parseFloat(this.walletMoney)", parseFloat(this.walletMoney));
				// console.log("parseFloat(this.moneyWithoutCode) >= parseFloat(this.walletMoney)", parseFloat(this.moneyWithoutCode) >= parseFloat(this.walletMoney));
				// console.log(!this.moneyWithoutCode || parseFloat(this.moneyWithoutCode) >= parseFloat(this.walletMoney));
				//如果免密金额大于等于当前当前钱包支付金额，则不用输密码
				if(!this.moneyWithoutCode || parseFloat(this.moneyWithoutCode) >= parseFloat(this.walletMoney)) {
					return true;
				}
			},
			//判断是否设置过密码
			passwordIsSet() {
				// return false;
				//1为设置过密码
				return this.userInfo.walletStatus === "1";
			},
			//等待密码校验的promise
			waitPasswordInputAndReg() {
				return new Promise((resolve, reject) => {
					this.timer = setInterval(() => {
						//密码错误不会结束pending状态
						//忘记密码就要结束pending状态
						//resultCode: 2, 忘记密码
						// 一旦密码校验状态结束
						if(!this.pwPendingResult.pwPendingState) {
							if(this.pwPendingResult.resultCode === 2) {
								clearInterval(this.timer);
								this.timer = null;
								resolve(this.pwPendingResult);
								return;
							}
							resolve(this.pwPendingResult);
							clearInterval(this.timer);
							this.timer = null;
						} else if(!this.pwPendingResult.result) {
							//密码校验失败
							this.mToastFn(this.pwPendingResult.msg);
							//重新置为初始状态，等待用户下一次输入
							this.pwPendingResult.result = "initial";
						}
					}, 100);
				});
			},
			mToastFn(message, duration = 1000, type = "warn") {
				Toast({
					message,
					type,
					duration
				});
			},
			//当输入密码组件校验完毕后改变pending值
			passwordPendingChangeEvent(obj) {
				//接收到一个对象
				this.pwPendingResult = obj;
			},
			//在vuex中置一个标志位为true，用来监控原生back键的返回
			setNativeBackFlagForPayIsTrue() {
				this.$store.commit("setNativeBackFlagForPay", true);
			},
			
		},
		components: {
			"m-pay": Pay,
			"passward-panel": passwardPanel,
		},
		watch: {
			//监听子组件中操作支付方式
			getPayWay(newVal) {
				// console.log("支付方式发生改变", newVal);
				//当钱包支付方式取消掉并且翌支付是勾选状态，自动把翌支付的金额变为订单金额
				if(!this.walletChoosed && this.yizhifuChoosed) {
					// console.log("勾选掉了钱包支付", this.totalMoney);
					this.thirdPayMoney = this.totalMoney;
					this.walletMoney = "0.00";
				} else if(this.walletChoosed && !this.yizhifuChoosed) {
					//如果钱包勾选并且翌支付没有勾选，则需要判断钱包可用金额是否大于等于订单金额
					//如果是，则将订单金额赋给钱包金额，
					//否则将可用金额赋给钱包金额
					this.walletMoney = parseFloat(this.walletBalance) >= parseFloat(this.totalMoney) ?
						this.totalMoney : this.walletBalance;
					//勾选上了钱包支付
				} else if(this.walletChoosed && this.yizhifuChoosed) {
					//两者都勾选，则翌支付金额为订单总金额减去钱包支付金额
                    let walletMoney = parseFloat(this.walletMoney) || 0;
					this.thirdPayMoney = (parseFloat(this.totalMoney) - walletMoney).toFixed(2);
				}
			}
		},
		created() {
			showLoading();
			//初始化翌支付
			this.initData();
			// this.setNativeBackFlagForPayIsTrue();
			console.log("this.orderNo", this.orderNo);
		}
	}
</script>

<style>

</style>